package com.tronsis.distribution.activity.training;

import android.Manifest;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.tronsis.distribution.Constants;
import com.tronsis.distribution.R;
import com.tronsis.distribution.bean.TeamTrainerBean;
import com.tronsis.distribution.biz.factory.TeamBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.library.activity.ToolBarBaseActivity;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.adapter.recyclerview.wrapper.LoadMoreWrapper;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.DownloadUtil;
import com.tronsis.library.util.EasyPermissions;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.CircleImageView;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class ContactsActivity extends ToolBarBaseActivity {

    @BindView(R.id.rv_contacts)
    RecyclerView mRvContacts;
    @BindView(R.id.srl_message)
    SwipeRefreshLayout mSrl;

    private CommonAdapter<TeamTrainerBean> mContactsAdapter;
    private List<TeamTrainerBean> mContactsList = new ArrayList<>();

    private int mPage = 1;
    private int mSize = 15;
    private int mTotal;
    private LoadMoreWrapper mLoadMoreWrapper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contacts);
        ButterKnife.bind(this);
        setTitle(true, getString(R.string.team_train));

        initContactsRv();
        httpTrainer(mPage, mSize, true);
    }

    private void initContactsRv() {
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpTrainer(mPage, mSize, true);
            }
        });
        mContactsAdapter = new CommonAdapter<TeamTrainerBean>(mContext, mContactsList, R.layout.item_contacts) {
            @Override
            protected void convert(ViewHolder holder, final TeamTrainerBean teamTrainerBean, int position) {
                CircleImageView iv = holder.getView(R.id.iv_avatar);
                ImageLoader.displayAvatar(mContext, Url.FILE_DOWNLOAD + teamTrainerBean.getAvatarFid(), iv);
                holder.setText(R.id.tv_name, teamTrainerBean.getName());
                if (position == 0 && teamTrainerBean.getJob() == null) {
                    holder.setText(R.id.tv_job, "销售经理");
                } else {
                    holder.setText(R.id.tv_job, teamTrainerBean.getJob());
                }
                holder.setOnClickListener(R.id.bt_wechat, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showDialog(teamTrainerBean.getWechatVcardFid());
                    }
                });
            }
        };

        mLoadMoreWrapper = new LoadMoreWrapper(mContactsAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.rv_load_more);
        mLoadMoreWrapper.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mContactsList.size() % 15 == 0 && mContactsList.size() > 0 && mContactsList.size() < mTotal) {
                    mPage = (mContactsList.size() / 15) + 1;
                    httpTrainer(mPage, mSize, false);
                }
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvContacts.addItemDecoration(decoration);
        mRvContacts.setLayoutManager(new LinearLayoutManager(mContext));
        mRvContacts.setAdapter(mLoadMoreWrapper);
    }


    private void httpTrainer(int page, int size, final boolean isRefresh) {
        try {

            TeamBizFactory.createBiz().listMyTrainer(this, page, size, new UICallBack() {
                @Override
                public void onStart() {
                    mSrl.setRefreshing(true);
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    List<TeamTrainerBean> list = listBean.getList();
                    if (isRefresh) {
                        mContactsList.clear();
                        mContactsList.addAll(list);
                    } else {
                        mContactsList.addAll(list);
                    }
                    mTotal = listBean.getTotal();
                    mLoadMoreWrapper.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);
                }
            });

        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }

    private void showDialog(final String wechatVcardFid) {
        if (StringUtil.isBlank(wechatVcardFid)) {
            ToastUtil.showMessage(mContext, "未找到微信二维码");
            return;
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_wechat, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(mContext).setView(view).create();

        ImageView ivQrCode = view.findViewById(R.id.iv_qr_code);
        ImageLoader.display(mContext, Url.FILE_DOWNLOAD + wechatVcardFid, ivQrCode);
        dialog.show();
        ImageButton btnClose = view.findViewById(R.id.mbt_close);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        Button btnSave = view.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EasyPermissions.hasPermissions(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    dialog.dismiss();
                    httpDownload(wechatVcardFid);
                } else {
                    EasyPermissions.requestPermissions(mContext,getString(R.string.perm_tip),0x111,Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }
            }
        });
    }

    private void httpDownload(final String id) {
        showLoadingDialog();
        DownloadUtil.get().download(Url.FILE_DOWNLOAD + id, Constants.SYSTEM_IMAGE_PATH, id + ".png", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
               runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showMessage(mContext, "下载完成");
                        MediaScannerConnection.scanFile(mContext, new String[]{Constants.SYSTEM_IMAGE_PATH + File.separator + id + ".png"}, new String[]{"image/jpeg"}, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Log.d("scanFile", "onScanCompleted : " + path);
                            }
                        });
                    }
                });
            }


            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed() {
               runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showMessage(mContext, "下载失败");
                    }
                });
            }
        });

    }
}
